package com.shun.oss.service;

import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Bucket;
import com.shun.common.utils.SpringContextUtil;
import com.shun.oss.config.OSSConfig;
import com.shun.oss.config.OSSConfigProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 阿里云对象存储服务类
 * @author clever
 * @since 2021-10-16
 */
@Slf4j
public class OssBaseService {

    /**
     * 管理者类型
     */
    private final static String OSS_MGR_TYPE = "0";

    /**
     * 读取者类型
     */
    private final static String OSS_CST_TYPE = "1";

    /**
     * 获取bucket的Name
     * @return
     */
    public String getBucketName(){
        OSSConfigProperties properties = SpringContextUtil.getBean(OSSConfig.OSS_MGR);
        return properties.getBucketName();
    }

    /**
     * 获取OSS实例
     * @return
     */
    public OSS getOssClient(String type){
        log.debug("创建ossClient。类型:{}",type);
        OSSConfigProperties properties = null;
        if(type.equals("0")){
            properties = SpringContextUtil.getBean(OSSConfig.OSS_MGR);
        }else{
            properties = SpringContextUtil.getBean(OSSConfig.OSS_CST);
        }
        log.debug("oss的配置信息:{}",properties);
        OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(),properties.getAccesKeyId(),properties.getAccessKeySecret());
        log.debug("创建成功OSSClient对象");
        return ossClient;
    }

    /**
     * 获得管理的权限
     * @return
     */
    public OSS getMgrOssClient(){
        return getOssClient(OSS_MGR_TYPE);
    }

    /**
     * 获得OSS的URL
     * @return
     */
    public String getUrl(){
        OSSConfigProperties properties = SpringContextUtil.getBean(OSSConfig.OSS_MGR);
        return properties.getEndpoint();
    }

    /**
     * 获得OSS的bucket的URL
     * @return
     */
    public String getBucketUrl(){
        OSSConfigProperties properties = SpringContextUtil.getBean(OSSConfig.OSS_MGR);
        return properties.getBucketUrl();
    }

    /**
     * 获得OSS的私有化文件超时单位小时
     * @return
     */
    public int getTimeout(){
        OSSConfigProperties properties = SpringContextUtil.getBean(OSSConfig.OSS_MGR);
        return properties.getTimeOut();
    }

    /**
     * 获取bucket列表
     * @return
     */
    public List<Bucket> getBuckets(){
        log.debug("获取bucket列表");
        OSS ossClient = getCstOssClient();
        List<Bucket> buckets = ossClient.listBuckets();
        buckets.forEach(s ->{System.out.println(JSONUtil.toJsonPrettyStr(s));});
        closeOss(ossClient);
        return buckets;
    }

    /**
     * 获得普通的权限
     * @return
     */
    public OSS getCstOssClient(){
        return getOssClient(OSS_CST_TYPE);
    }

    /**
     * 关闭oss对象
     * @param ossClient
     */
    public void closeOss(OSS ossClient){
        ossClient.shutdown();
    }
}
